<script lang="ts">
import { Component, Vue, Prop } from 'vue-property-decorator'
import { CreateElement } from 'vue'

@Component({
  name: 'RenderImage'
})
export default class extends Vue {
  // button text
  @Prop({ type: String, required: false, default: 'show image' })
  private placeholder!: string
  // display mode, button or image
  @Prop({ type: Boolean, required: false, default: false })
  private isImage!: boolean

  private handlePreview (url: string) {
    this.$emit('preview', url)
  }

  render (h: CreateElement) {
    return h('el-table-column', {
      props: this.$attrs,
      scopedSlots: {
        default: ({ row }) => {
          const url = row[this.$attrs.prop]

          const image = h(
            'div',
            {
              style: {
                maxHeight: '150px',
                maxWidth: '150px',
                cursor: 'pointer'
              },
              on: {
                click: () => {
                  this.handlePreview(url)
                }
              }
            },
            [
              h('el-image', {
                attrs: { alt: this.$attrs.prop },
                props: { src: url, fit: 'contain' }
              })
            ]
          )

          const button = h(
            'el-button',
            {
              props: { type: 'text' },
              on: {
                click: () => {
                  this.handlePreview(url)
                }
              }
            },
            this.placeholder
          )

          return url ? (this.isImage ? image : button) : null
        }
      }
    })
  }
}
</script>
